<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Log;
use xmltool\Xml2Object;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    const  FILE_EXT_LIST=[
            'JPG','PNG','WEBP',
            'DOC','DOCX','XLS',
            'XLSX','PPT','PPTX',
    ];
    protected function errorSend($code,$msg,$data){
        return response()->json(
            compact(
                'code','msg','data'
            ),500
        );
    }
    protected function passSend($code,$msg,$data){
        return response()->json(
            compact(
                'code','msg','data'
            )
        );
    }
    protected function validateForm($data,$role,$msg){
        return $this->getValidationFactory()->make($data,$role,$msg);
    }
    protected function requestModel(string $table,Request $request,bool $update=false){
        try{
        $exts=self::FILE_EXT_LIST;
        $xml=Xml2Object::getInstance();
        $parsed=$xml->parse(Xml2Object::TABLEXML_SAVE_PATH.$table.'.xml');
        $listener=$parsed[$table]['listener'];
        $oprater=$parsed[$table][$update?'update':'insert'];
        $params=[];
        $updateKeys=[];
        foreach($oprater as $k=>$v){
            if($update){
                $val=$request->json($k);
                $isKey=$v['key']??null;
                if(empty($v['auto'])){
                    if(!empty($isKey)){
                        if($val!==null){
                            $updateKeys[$k]=$val;
                        }
                    }else{
                        if($val!==null){
                            $params[$k]=$val;
                        }
                    }
                }
            }else{
                if(empty($v['auto']))
                $params[$k]=$request->json($k,$this->defaultValue($v,$table));
            }
        }
        if($update){
            $params['__keys']=$updateKeys;
        }
        return [
            $params,
            $listener[$update?'update':'insert']
        ];
        }catch(Exception $e){
            $err=$e->getFile()." ".$e->getLine()." ".$e->getCode()." ".$e->getMessage().PHP_EOL;
            $err.=$e->getTraceAsString().PHP_EOL;
            Log::error($err);
            return [null,null];
        }
    }
    private function defaultValue($field,$table){
        switch($field['default']){
            case 'uniqid':
                return uniqid($table.'_').'_'.mt_rand(10000,100000);
            default:
                return $this->defaulTypeValue($field,$table);
        }
    }
    private function defaulTypeValue($field,$table){
        $dft=$field['default']??null;
        if(!empty(preg_match("/int/",$field['type']))){
            return intval($dft);
        }
        if(!empty(preg_match("/timestamp/",$field['type']))){
            if($dft=='now'){
                return  date('Y-m-d H:i:s');
            }elseif($dft=='date'){
                return  date('Y-m-d',);
            }elseif($dft=='date_set'){
                return  date('Y-m-d',strtotime($dft));
            }elseif($dft=='datetime_set'){
                return  date('Y-m-d H:i:s',strtotime($dft));
            }else{
                return null;
            }
        }
    }
    public function emitEvent($action,$model){
        return Xml2Object::emitEvent($action,$model);
    }
}
